<?php

namespace app\admin\controller\workflow;

use app\common\controller\Backend;
use app\common\model\workflow\Workflow as WorkflowModel;
use think\Exception;
use think\facade\Db;
use think\Request;

class Workflow extends Backend
{
    protected array $noNeedPermission = ['detail', 'audit'];
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(): void
    {
        try {
            $res = WorkflowModel::list($this->auth->getAdmin()->toArray());
            $this->success('', [
                'list' => $res->items(),
                'total' => $res->total()
            ]);
        } catch (Exception $e){
            $this->error($e->getMessage().$e->getFile().$e->getLine());
        }
    }

    /**
     * 资源详情
     *
     * @return \think\Response
     */
    public function detail(Request $request): void
    {
        try {
            $no = $request->post('no');
            $detail = WorkflowModel::with(['nodes','records','scopes'])->where('flow_no',$no)->find();
            $this->success('', $detail);
        } catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    public function audit():void
    {
        Db::startTrans();
        try {
            $data = $this->request->post();
            $wfservice = new \app\common\service\workflow\WorkFlow($data['flow_no'], $this->auth->getAdmin()->toArray());
            $wfservice->audit($data, $this->auth->getAdmin()->toArray());
            Db::commit();
            $this->success('审核成功！');
        } catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage().'||'.$e->getFile().'||'.$e->getLine());
        }
    }
}
